import processing.serial.*;      //load a library processing.serial
Serial serialPort;               //serial port
//Set previous value of plots
int previousPosition  = 0;       
int previousHeight = 0;          
int currentPosition = 0;         //set the initial value of current position in x-axis  

void setup (){
  size(700,700);                                              //set the size of window       
  println(Serial.list());                                     //list all available serial ports
  serialPort = new Serial(this, Serial.list()[0], 9600);      //open the port using the baud rate corresponding to Arduino:
  serialPort.bufferUntil('\n');                               //while a newline charcter is obtained, the serialEvent() is created
  background(0);                                              //set the initial background as black
}

void draw(){
  
}

void serialEvent(Serial serialPort){
  String inputString = serialPort.readStringUntil('\n');      //obtain the input string from the port
  if (inputString != null) {     
    inputString = trim(inputString);                          //remove whitespace  characters
    float inputNumber = float(inputString);                   //convert the string to the number value
    inputNumber = map(inputNumber, 0, 1000, 0, height);      //map the input number to the size of window

    //Draw a line
    stroke(255,255,255);                                                                    //line with white colour
    strokeWeight(2);                                                                        //line with weight of 2
    line(previousPosition, previousHeight, currentPosition, height-inputNumber);            //draw a line
    previousPosition = currentPosition;                                                     //move the current position to the previous position
    previousHeight = int(height-inputNumber);                                               //move the current height to the previous height   

    //At the edge (last position)
    if (currentPosition >= width) {
      currentPosition = 0;                                    //set back to the initial value
      previousPosition = 0;                                   //set back to the initial value
      background(0);                                          //clear to the black screen
    } 
    else {
      currentPosition++;                                                 //increase the position by 1
    }
    
  }
}


